package org.boulderfoodrescue.webapp.client.options.manageusers;

import org.boulderfoodrescue.webapp.client.managers.UserAccountManager;
import org.boulderfoodrescue.webapp.client.options.OptionsInterface;
import org.boulderfoodrescue.webapp.shared.UserAccount;
import org.boulderfoodrescue.webapp.shared.UserAccountDetails.AccessLevel;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class ManageUsersPanel extends Composite {

  private static ManageusersPanelUiBinder uiBinder = GWT
      .create(ManageusersPanelUiBinder.class);

  interface ManageusersPanelUiBinder extends UiBinder<Widget, ManageUsersPanel> {
  }

  public ManageUsersPanel(UsersCellTable uTable, OptionsInterface optionsInterface) {
    this.optionsInterface = optionsInterface;
    usersCellTable = uTable;
    initWidget(uiBinder.createAndBindUi(this));
  }


  @UiField
  TextBox firstName;
  @UiField
  TextBox lastName;
  @UiField
  TextBox email;
  @UiField
  TextBox email2;
  @UiField
  ListBox accessLvl;
  @UiField(provided=true)
  UsersCellTable usersCellTable;
  @UiField 
  Button addUser;

  private OptionsInterface optionsInterface;
  
  @UiHandler("addUser")
  public void onAddUserClick(ClickEvent e){
    if(!email.getText().equals(email2.getText()) || email == null) {
      Window.alert("Email Addresses are not consistent");
      return;
    }
    if(!email.getText().contains("@gmail.com") && !email.getText().contains("@boulderfoodrescue.org"))
    {
      Window.alert("Email Addresses must be gmail.com/boulderfoodrescue.org accounts");
      return;
    }
    addUser.setEnabled(false);
    addUser.setText("Please wait...");
    final UserAccount user = new UserAccount();

    user.setFirstName(firstName.getText());
    user.setLastName(lastName.getText());
    user.setEmail(email.getText());
    int access = accessLvl.getSelectedIndex();
    switch(access)
    {
    case 0: user.setAccessLevel(AccessLevel.Public); break;
    case 1: user.setAccessLevel(AccessLevel.Volunteer);break;
    case 2: user.setAccessLevel(AccessLevel.Admin);break;
    }

    firstName.setText("");
    lastName.setText("");
    email.setText("");
    email2.setText("");
    accessLvl.setSelectedIndex(0);

    optionsInterface.onAddingNewUser(user);
    
    UserAccountManager.addUser(user);
  }
  
  public void onAddUserCompleted()
  {
    addUser.setEnabled(true);
    addUser.setText("Add User");
  }
}
